<?php
// +----------------------------------------------------------------------
// | Name 风音框架
// +----------------------------------------------------------------------
// | Author 唐启云 <tqy@fxri.net>
// +----------------------------------------------------------------------
// | Copyright Copyright © 2016-2099 方弦研究所. All rights reserved.
// +----------------------------------------------------------------------
// | Link https://www.fxri.net
// +----------------------------------------------------------------------

namespace fxsafe\facade;

/**
 * 书信类
 */
class Letter
{
    /**
     * 使用AK&SK初始化账号Client
     * @param string $accessKeyId
     * @param string $accessKeySecret
     * @return \AlibabaCloud\SDK\Dysmsapi\V20170525\Dysmsapi Client
     */
    public static function createClient($accessKeyId, $accessKeySecret)
    {
        // 初始化变量
        $config = new \Darabonba\OpenApi\Models\Config([
            // 必填，您的 AccessKey ID
            "accessKeyId" => $accessKeyId,
            // 必填，您的 AccessKey Secret
            "accessKeySecret" => $accessKeySecret
        ]);
        // 访问的域名
        $config->endpoint = "dysmsapi.aliyuncs.com";
        return new \AlibabaCloud\SDK\Dysmsapi\V20170525\Dysmsapi($config);
    }

    /**
     * @param string[] $param
     * @return mixed
     */
    public static function alisms($param)
    {
        // 初始化变量
        $config = \fxsafe\Config::get('letter.sms');
        // 请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_ID 和 ALIBABA_CLOUD_ACCESS_KEY_SECRET。
        // 工程代码泄露可能会导致 AccessKey 泄露，并威胁账号下所有资源的安全性。以下代码示例使用环境变量获取 AccessKey 的方式进行调用，仅供参考，建议使用更安全的 STS 方式，更多鉴权访问方式请参见：https://help.aliyun.com/document_detail/311677.html
        $client = self::createClient($config['app_id'], $config['app_secret']);
        // 疏理参数
        $predefined = [
            // 手机号
            'mobile' => null,
            // 短信签名
            'sign_name' => $config['sign_name'],
            // 模板CODE
            'tpl_code' => $config['tpl_code'],
            // 模板参数
            'tpl_param' => [],
        ];
        $param = \fxsafe\Param::define([$param, $predefined], '1.1.2');
        // 疏理手机号
        if (is_array($param['mobile'])) {
            $param['mobile'] = implode(',', $param['mobile']);
        }
        // 检查手机号
        if (is_blank($param['mobile'])) {
            return '请输入手机号';
        }
        // 疏理选项
        $option = [];
        $option['phoneNumbers'] = $param['mobile'];
        $option['signName'] = $param['sign_name'];
        $option['templateCode'] = $param['tpl_code'];
        $option['templateParam'] = \fxsafe\Base::json($param['tpl_param'], 'encode');
        $sendSmsRequest = new \AlibabaCloud\SDK\Dysmsapi\V20170525\Models\SendSmsRequest($option);
        $runtime = new \AlibabaCloud\Tea\Utils\Utils\RuntimeOptions([]);
        try {
            // 复制代码运行请自行打印 API 的返回值
            $record = $client->sendSmsWithOptions($sendSmsRequest, $runtime);
            // 返回结果
            if (!is_object($record) || !isset($record->body->code)) {
                return '发送失败';
            } else if ($record->body->code == 'OK') {
                return true;
            } else if ($record->body->code != 'OK') {
                return $record->body->message . ' - ' . $record->body->code;
            }
        } catch (\Exception $error) {
            if (!($error instanceof \AlibabaCloud\Tea\Exception\TeaError)) {
                $error = new \AlibabaCloud\Tea\Exception\TeaError([], $error->getMessage(), $error->getCode(), $error);
            }
            // 如有需要，请打印 error
            \AlibabaCloud\Tea\Utils\Utils::assertAsString($error->message);
            // 返回错误信息
            return $error->message;
        }
    }
}
